# coding: utf-8
from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import json


class ModelManagerGiveTimeActivity(BasicManager):
    # 获取vip列表
    def get_activity_list(self, page, is_show=None, types=None):
        result = self.values().order_by("-created_at")
        if is_show:
            result = result.filter(is_show=is_show)
        if types:
            result = result.filter(types=types)
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        paginator = Paginator(result, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}


class ModelManagerClassification(BasicManager):

    def get_classification_list(self, page, type=1, status=None):
        result = self.filter(is_delete=0, types=type).values("id", "name", "sort", "pid").order_by("-sort")
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        if status:
            result = result.filter(pid=0)
        paginator = Paginator(result, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        if status:
            for v in result_page:
                if int(type) == 1:
                    v['use'] = mm_ClassificationMessage.filter(is_delete=0, status=0, classification_id=v['id']).count()
                    v['disable'] = mm_ClassificationMessage.filter(is_delete=0, status=1, classification_id=v['id']).count()
                if int(type) == 2:
                    v['use'] = mm_ClassificationCollege.filter(is_delete=0, status=0, classification_id=v['id']).count()
                    v['disable'] = mm_ClassificationCollege.filter(is_delete=0, status=1, classification_id=v['id']).count()
                v['subclass'] = list(self.filter(pid=v['id']).values("name", "id"))
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def creates(self, name, types, permission_id, pid=None):
        res = self.create(
            name=name,
            types=types,
            pid=pid
        )
        permission = json.loads(permission_id)
        for v in permission:
            mm_ClassificationJurisdiction.create(
                classification_id=res.id,
                permission_id=v
            )

    def delete(self, id):
        res = self.get_or_default(id=id)
        if res.types == 1:
            result = mm_ClassificationMessage.filter(classification_id=id).values().first()
            if result:
                return {'retcode': 1, 'msg': '改分类下有素材不可删除'}
        if res.types == 2:
            result = mm_ClassificationCollege.filter(classification_id=id).values().first()
            if result:
                return {'retcode': 1, 'msg': '改分类下有素材不可删除'}
        self.filter(id=id).update(is_delete=1)
        return {'retcode': 0, 'msg': 'OK'}
        # ClassificationMessage.objects.filter(classification_id=id).update(is_delete=1)


class ModelManagerClassificationMessage(BasicManager):

    def get_wechat_list(self, page, classification_id=None, title=None, status=None, start_date=None, end_date=None,
                        level=None, search=None):
        result = self.filter(is_delete=0).values("title", "imgs", "content", "id", "created_at", "status", 'video',
                                                 "classification__name", "duration", "shape").order_by("-created_at")
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        if search:
            result = result.filter(content__icontains=search)
        if classification_id:
            subclass = mm_Classification.filter(pid=classification_id).values('id')
            ids = [i['id'] for i in subclass]
            ids.append(classification_id)
            result = result.filter(classification_id__in=ids)
        if level:
            level_list = []
            if level in [1, 2, 3]:
                level_list = [1]
            if level in [4, 5, 6]:
                level_list = [2]
            result = result.filter(classificationmjurisdiction__permission_id__in=level_list)
        if title:
            result = result.filter(title=title)
        if status or status == "0":
            result = result.filter(status=status)
        if start_date and end_date:
            result = result.filter(created_at__range=[start_date, end_date])
        paginator = Paginator(result, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages, "head":
                    "http://cdn-web-img.momself.cn/stu_/FlFqifveTifl6kXZ-mkovUUuT_vC.png"}

    def get_detail(self, id):
        result = self.filter(id=id).values("title", "imgs", "content", "id", "created_at", "video",
                                           "classification_id", "duration").first()
        return result

    def creates(self, title, classification_id, imgs, video, content, duration, shape, permission_id):
        res = self.create(
            title=title,
            classification_id=classification_id,
            imgs=imgs,
            video=video,
            content=content,
            duration=duration,
            shape=shape
        )
        permission = json.loads(permission_id)
        for v in permission:
            mm_ClassificationMJurisdiction.create(
                classificationm_id=res.id,
                permission_id=v
            )

    def delete(self, id):
        self.filter(id=id).update(is_delete=1)


class ModelManagerClassificationCollege(BasicManager):

    def get_subclass_list(self, page, title=None, classification_id=None, status=None, start_date=None, end_date=None,
                          level=None, search=None):
        result = self.filter(is_delete=0).values("title", "types", "resources", "content", "id", "created_at", "img",
                                                 "duration", "classification__name", "status").order_by("-created_at")
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        if search:
            result = result.filter(title__icontains=search)
        if classification_id:
            subclass = mm_Classification.filter(pid=classification_id).values('id')
            ids = [i['id'] for i in subclass]
            ids.append(classification_id)
            result = result.filter(classification_id__in=ids)
        if level:
            level_list = []
            if level in [1, 2, 3]:
                level_list = [1]
            if level in [4, 5, 6]:
                level_list = [2]
            result = result.filter(classificationcjurisdiction__permission_id__in=level_list)
        if title:
            result = result.filter(title=title)
        if status or status == "0":
            result = result.filter(status=status)
        if start_date and end_date:
            result = result.filter(created_at__range=[start_date, end_date])
        paginator = Paginator(result, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_detail(self, id):
        result = self.filter(id=id).values("title", "types", "resources", "content", "id", "created_at",
                                           "duration", "img").first()
        return result

    def creates(self, title, classification_id, img, resources, content, types, duration, permission_id):
        res = self.create(
            title=title,
            classification_id=classification_id,
            img=img,
            resources=resources,
            content=content,
            types=types,
            duration=duration
        )
        permission = json.loads(permission_id)
        for v in permission:
            mm_ClassificationCJurisdiction.create(
                classificationc_id=res.id,
                permission_id=v
            )

    def delete(self, id):
        self.filter(id=id).update(is_delete=1)


class ModelManagerProblem(BasicManager):

    def get_list(self, page, title=None, identity=None, level=1):
        if level > 0 and level != 10:
            result = self.filter(identity__in=[2, 3]).values().order_by("-created_at")
        else:
            result = self.filter(identity__in=[1, 3]).values().order_by("-created_at")
        if title:
            result = result.filter(title=title)
        if identity:
            result = result.filter(identity=identity)
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        paginator = Paginator(result, 10)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def creates(self, title, identity, content):
        self.create(
            title=title,
            identity=identity,
            content=content
        )

    def delete(self, id):
        self.filter(id=id).delete()


class ModelManagerClassificationJurisdiction(BasicManager):
    pass


class ModelManagerClassificationMJurisdiction(BasicManager):
    pass


class ModelManagerClassificationCJurisdiction(BasicManager):
    pass


class GiveTimeActivity(models.Model):
    name = models.CharField("活动名称", max_length=50)
    is_show = models.PositiveSmallIntegerField("活动状态", default=1)  # 1: 进行中  0:关闭中
    day = models.IntegerField('赠送天数', default=0)  # 单位：天
    activity_strtime = models.DateTimeField("活动开始时间")
    activity_endtime = models.DateTimeField("活动结束时间")
    types = models.PositiveSmallIntegerField("类型", default=1)  # 类型  1:课程VIP399  2:优势大学卡1499
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerGiveTimeActivity()

    class Meta:
        verbose_name = 'vip时间赠送活动'
        verbose_name_plural = verbose_name
        db_table = "momself_freetime_activity"

    def __str__(self):
        return self.name


class Classification(models.Model):
    name = models.CharField("分类名称", max_length=20)
    sort = models.IntegerField("排序", default=0)
    types = models.PositiveSmallIntegerField("类别", default=1)  # 1:代表发圈素材  2:商学院
    pid = models.IntegerField("父类id", default=0)
    is_delete = models.PositiveSmallIntegerField("伪删除", default=0)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerClassification()

    class Meta:
        verbose_name = '素材分类表'
        verbose_name_plural = verbose_name
        db_table = "momself_classification"


class ClassificationJurisdiction(models.Model):
    classification = models.ForeignKey(Classification)
    permission_id = models.IntegerField("权限", default=0)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerClassificationMessage()

    class Meta:
        verbose_name = '分类权限表'
        verbose_name_plural = verbose_name
        db_table = "momself_classification_jurisdiction"


class ClassificationMessage(models.Model):
    title = models.CharField("素材标题", max_length=100)
    classification = models.ForeignKey(Classification)
    imgs = models.TextField("朋友圈图片", default='', blank=True)
    video = models.CharField("视频链接", default='', blank=True, max_length=200)
    content = models.TextField("素材内容", default='', blank=True)
    is_delete = models.PositiveSmallIntegerField("伪删除", default=0)  # 0:展示  1:删除
    status = models.PositiveSmallIntegerField("状态", default=0)  # 0:展示  1:隐藏
    duration = models.IntegerField("时长(秒数)", default=0)
    shape = models.PositiveSmallIntegerField("视频是横屏还是竖屏", default=1)  # 1是横屏  2是竖屏
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerClassificationMessage()

    class Meta:
        verbose_name = '素材朋友圈'
        verbose_name_plural = verbose_name
        db_table = "momself_classification_message"


class ClassificationCollege(models.Model):
    title = models.CharField("商学院素材标题", max_length=100)
    classification = models.ForeignKey(Classification)
    img = models.TextField("商学院主图", default='')
    types = models.PositiveSmallIntegerField("类型", default=0)   # 0:图文 1:视频 2:音频
    resources = models.CharField("音视频资源", max_length=200)
    content = models.TextField("素材内容", default='', blank=True)
    is_delete = models.PositiveSmallIntegerField("伪删除", default=0)  # 0:展示  1:删除
    status = models.PositiveSmallIntegerField("状态", default=0)  # 0:展示  1:隐藏
    duration = models.IntegerField("时长(秒数)", default=0)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerClassificationCollege()

    class Meta:
        verbose_name = '素材商学院'
        verbose_name_plural = verbose_name
        db_table = "momself_classification_college"


class ClassificationMJurisdiction(models.Model):
    classificationm = models.ForeignKey(ClassificationMessage)
    permission_id = models.IntegerField("权限", default=0)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerClassificationMJurisdiction()

    class Meta:
        verbose_name = '朋友圈权限表'
        verbose_name_plural = verbose_name
        db_table = "momself_classificationm_jurisdiction"


class ClassificationCJurisdiction(models.Model):
    classificationc = models.ForeignKey(ClassificationCollege)
    permission_id = models.IntegerField("权限", default=0)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerClassificationCJurisdiction()

    class Meta:
        verbose_name = '商学院权限表'
        verbose_name_plural = verbose_name
        db_table = "momself_classificationc_jurisdiction"


class Problem(models.Model):
    title = models.CharField("问题", max_length=100)
    content = models.TextField("素材内容", default='', blank=True)
    identity = models.PositiveSmallIntegerField("身份", default=1)  # 1:仅c端普通用户  2:仅代言人用户 3:都可
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerProblem()

    class Meta:
        verbose_name = '常见问题'
        verbose_name_plural = verbose_name
        db_table = "momself_problem"


mm_GiveTimeActivity = GiveTimeActivity.objects
mm_Classification = Classification.objects
mm_ClassificationMessage = ClassificationMessage.objects
mm_ClassificationCollege = ClassificationCollege.objects
mm_Problem = Problem.objects
mm_ClassificationJurisdiction = ClassificationJurisdiction.objects
mm_ClassificationMJurisdiction = ClassificationMJurisdiction.objects
mm_ClassificationCJurisdiction = ClassificationCJurisdiction.objects


